<template>
  <a-modal :open="open" :width="type === '血糖监测' ? '950px' : '850px'" :title="type" centered @cancel="onCancel" @ok="onOk">
    <div class="w-full flex">
      <div class="w-1/3 pr-2">
        <!-- <BaseTitle title="信息" /> -->
        <BedCard :data="data" class-name="flex-center py-12" active />
      </div>
      <div class="w-2/3 pl-6 border-l-2">
        <a-form :model="formState" :label-col="{ span: 7 }" class="mt-2">
          <template v-if="type === '转区'">
            <BaseTitle :title="type" />

            <a-form-item label="接收科室">
              <a-input :value="data.inpTransferZone?.destDeptName" disabled />
            </a-form-item>
            <a-form-item label="接收病区">
              <a-input :value="data.inpTransferZone?.destWardName" disabled />
            </a-form-item>
            <a-form-item label="转区时间">
              <a-date-picker v-model:value="formState.zcsj" class="w-full" show-time value-format="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>
            <a-form-item name="cmemo" label="嘱托">
              <a-textarea v-model:value="formState.cmemo" placeholder="请输入" />
            </a-form-item>
          </template>
          <template v-else-if="type === '换床'">
            <a-form-item label="原床位">
              {{ data.lastBedCode || '无' }}
            </a-form-item>
            <a-form-item label="新床位">
              <SelectTable
                v-model:value="formState.targetBedCode"
                type="床位"
                :table-width="400"
                :search-params="{ bqid: areaStore.areaCode }"
                placeholder="请输入"
                :row-disabled="(row) => row.status === 2 || row.status === 1"
                @select="(item) => (formState.targetBedCode = item.bedCode)"
              />
            </a-form-item>
          </template>
          <template v-else-if="type === '换医生'">
            <BaseTitle :title="type" />

            <a-form-item label="主管医生">
              <SelectTable v-model:value="formState.zgysmc" type="医生" @select="onSelectDocker($event, 'zgys')" />
            </a-form-item>
            <a-form-item label="床位医生">
              <SelectTable v-model:value="formState.cwysmc" type="医生" @select="onSelectDocker($event, 'cwys')" />
            </a-form-item>
            <a-form-item label="主治医生">
              <SelectTable v-model:value="formState.zzysmc" type="医生" @select="onSelectDocker($event, 'zzys')" />
            </a-form-item>
          </template>
          <template v-else-if="type === '更换护理等级'">
            <BaseTitle :title="type" />

            <a-form-item label="原护理等级">
              {{ formState.nurseLevelName || '无' }}
            </a-form-item>
            <a-form-item label="新护理等级">
              <SelectLevel v-model:value="formState.levelId" trigger="focus" />
            </a-form-item>
          </template>
          <div v-else-if="type === '血糖监测'" class="xt-style-flex">
            <a-form-item label="血糖监测" class="w-1/5" :label-col="{ span: 15 }">
              <a-switch v-model:checked="formState.bgStatus" :un-checked-value="0" :checked-value="1" @change="onChangeMonitors" />
            </a-form-item>
            <a-form-item label="" class="w-4/5 flex justify-center" :label-col="{ span: 2 }">
              <a-button type="primary" ghost @click="checkDay('0')">前一天</a-button>
              <a-date-picker v-model:value="recordDate" value-format="YYYY-MM-DD" class="mx-2 !w-32" />
              <a-button type="primary" ghost @click="checkDay('1')">后一天</a-button>
            </a-form-item>
            <BaseTitle title="指尖血糖" />
            <div class="w-full form-style-flex flex items-center border">
              <div class="w-1/4 h-[35px] flex items-center pl-2">早餐前</div>
              <div class="w-1/4 h-[35px] border-x">
                <BaseInput v-model:value="monitorsData.breakfastBefore" v-input:float class="border-0 h-full w-full" placeholder="请输入" />
              </div>
              <div class="w-1/4 h-[35px] flex items-center pl-2">早餐后</div>
              <div class="w-1/4 h-[35px] border-x">
                <BaseInput v-model:value="monitorsData.breakfastAfter" v-input:float class="border-0 h-full w-full" placeholder="请输入" />
              </div>
            </div>
            <div class="w-full form-style-flex flex items-center border border-t-0">
              <div class="w-1/4 h-[35px] flex items-center pl-2">午餐前</div>
              <div class="w-1/4 h-[35px] border-x">
                <BaseInput v-model:value="monitorsData.lunchBefore" v-input:float class="border-0 h-full w-full" placeholder="请输入" />
              </div>
              <div class="w-1/4 h-[35px] flex items-center pl-2">午餐后</div>
              <div class="w-1/4 h-[35px] border-x">
                <BaseInput v-model:value="monitorsData.lunchAfter" v-input:float class="border-0 h-full w-full" placeholder="请输入" />
              </div>
            </div>
            <div class="w-full form-style-flex flex items-center border border-t-0">
              <div class="w-1/4 h-[35px] flex items-center pl-2">晚餐前</div>
              <div class="w-1/4 h-[35px] border-x">
                <BaseInput v-model:value="monitorsData.dinnerBefore" v-input:float class="border-0 h-full w-full" placeholder="请输入" />
              </div>
              <div class="w-1/4 h-[35px] flex items-center pl-2">晚餐后</div>
              <div class="w-1/4 h-[35px] border-x">
                <BaseInput v-model:value="monitorsData.dinnerAfter" v-input:float class="border-0 h-full w-full" placeholder="请输入" />
              </div>
            </div>
            <div class="w-full form-style-flex flex items-center border border-t-0">
              <div class="w-1/4 h-[35px] flex items-center pl-2">睡前</div>
              <div class="w-1/4 h-[35px] border-x">
                <BaseInput v-model:value="monitorsData.sleepBefore" v-input:float class="border-0 h-full w-full" placeholder="请输入" />
              </div>
              <div class="w-1/4 h-[35px] flex items-center pl-2"></div>
              <div class="w-1/4 h-[35px] border-x"></div>
            </div>

            <BaseTitle title="短效RI/U" class="mt-2" />
            <a-form-item label="早" class="w-1/3" :label-col="{ style: { width: '80px' } }">
              <a-input v-model:value="monitorsData.shortMorning" type="number" placeholder="请输入" />
            </a-form-item>
            <a-form-item label="中" class="w-1/3" :label-col="{ style: { width: '45px' } }">
              <a-input v-model:value="monitorsData.shortMiddle" type="number" placeholder="请输入" />
            </a-form-item>
            <a-form-item label="晚" class="w-1/3" :label-col="{ style: { width: '45px' } }">
              <a-input v-model:value="monitorsData.shortEvening" type="number" placeholder="请输入" />
            </a-form-item>
            <a-divider class="mt-2 mb-4" />
            <a-form-item label="长效RI/U" class="w-1/2" :label-col="{ style: { width: '80px' } }">
              <a-input v-model:value="monitorsData.longValue" type="number" placeholder="请输入" />
            </a-form-item>
            <a-form-item label="备注" class="w-1/2" :label-col="{ style: { width: '70px' } }">
              <a-input v-model:value="monitorsData.memo" placeholder="请输入" />
            </a-form-item>

            <a-form-item label="记录时间" class="w-1/2" :label-col="{ style: { width: '80px' } }">
              <a-time-picker v-model:value="monitorsData.time" format="HH:mm" value-format="HH:mm" @change="(value) => (monitorsData.time = value || '')" />
            </a-form-item>
            <a-form-item label="记录人" class="w-1/2" :label-col="{ style: { width: '70px' } }">
              <!-- <a-input v-model:value="monitorsData.createUser" placeholder="请输入" /> -->
              <SelectTable v-model:value="monitorsData.createUserName" type="护士" @select="onSelectNurse" />
            </a-form-item>
          </div>
          <template v-else-if="type === '每日清单'">
            <a-form-item label="日期" :label-col="{ style: { width: '60px' } }" required>
              <a-date-picker v-model:value="formState.dyrq" value-format="YYYY-MM-DD" :allow-clear="false" />
            </a-form-item>
          </template>
        </a-form>
      </div>
    </div>
    <div v-if="type === '血糖监测'" class="absolute bottom-5 right-[170px]">
      <a-button @click="onPrint()">打印</a-button>
    </div>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import SelectTable from '@/components/SelectTable'
import BaseTitle from '@/components/BaseTitle'
import { post } from '@/utils/request'
import BedCard from '@/components/business/BedCard'
import useUserStore from '@/store/user'
import useStore from '../../store'

const areaStore = useStore()
const recordDate = ref(dayjs().format('YYYY-MM-DD'))
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  type: {
    type: String,
    default: ''
  },
  data: {
    type: Object,
    default: () => ({})
  }
})
const monitorsData = ref({})
const isPrint = ref(false)
const formState = ref({
  mbbq: '',
  zcsj: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  dyrq: dayjs().format('YYYY-MM-DD'),
  bgStatus: 0
})
const emit = defineEmits(['update:open', 'close', 'success'])

// 打印
const onPrint = async () => {
  const { code, msg, data } = await post('/inp/Print/printBloodGlucoseTestSlips', { inplsh: props.data.inplsh })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

const onOk = async () => {
  if (props.type === '转区') {
    const { code, msg } = await post('inp/zyhs/doTransferOutWard', {
      cmemo: formState.value.cmemo,
      mbbq: props.data.inpTransferZone?.destWardId,
      mbks: props.data.inpTransferZone?.destDeptCode,
      advId: props.data.inpTransferZone?.inpAdvId,
      zcsj: formState.value.zcsj,
      inplsh: props.data.inplsh
    })
    if (code !== 0) return message.error(msg || '操作失败')
    message.success('转出成功')
    emit('update:open', false)
    emit('success')
  } else if (props.type === '换床') {
    const { code, msg } = await post('/inp/zyhs/doChangingBed', {
      targetWardId: areaStore.areaCode,
      originalBedCode: props.data.lastBedCode,
      targetBedCode: formState.value.targetBedCode,
      inplsh: props.data.inplsh
    })
    if (code !== 0) return message.error(msg || '操作失败')
    message.success('换床成功')
    emit('update:open', false)
    emit('success')
  } else if (props.type === '更换护理等级') {
    const { code, msg } = await post('/inp/zyhs/doChangingNursingGrade', {
      levelId: formState.value.levelId,
      inplsh: props.data.inplsh
    })
    if (code !== 0) return message.error(msg || '操作失败')
    message.success('更换护理等级成功')
    emit('update:open', false)
    emit('success')
  } else if (props.type === '血糖监测') {
    const { code, msg } = await post(
      '/inp/zyhs/doSaveBGTestRecord',
      {
        ...monitorsData.value,
        inplsh: props.data.inplsh,
        testTime: recordDate.value
      },
      { loading: true }
    )
    if (code !== 0) return message.error(msg || '操作失败')
    message.success('保存成功')
    getMonitorsData()
    // emit('update:open', false)
    emit('success')
  } else if (props.type === '每日清单') {
    if (!formState.value.dyrq) return message.error('请选择日期')
    emit('update:open', false)
    onPrintEveryRecord()
  }
}
const onPrintEveryRecord = async () => {
  message.loading('打印中，请稍候...', 3)
  const { code, msg, data } = await post('/inp/Print/printAdmissionList', {
    inplsh: props.data.inplsh,
    dyrq: formState.value.dyrq,
    jslb: 'SF'
  })
  // message.destroy()
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
const onChangeMonitors = async () => {
  const { code, msg } = await post('/inp/zyhs/updatelnpBGTestStaus', {
    bgStatus: formState.value.bgStatus,
    inplsh: props.data.inplsh
  })
  if (code !== 0) return message.error(msg || '操作失败')
  message.success('操作成功')
  emit('success')
}

const checkDay = (type) => {
  if (type === '1') {
    recordDate.value = dayjs(recordDate.value).add(1, 'day').format('YYYY-MM-DD')
    getMonitorsData()
  } else {
    recordDate.value = dayjs(recordDate.value).subtract(1, 'day').format('YYYY-MM-DD')
    getMonitorsData()
  }
}
const onSelectDocker = (selected, key) => {
  formState.value[key] = selected.empId
  formState.value[key + 'mc'] = selected.empName
}
const userStore = useUserStore()
const getMonitorsData = async () => {
  const { code, msg, data } = await post('inp/zyhs/getBGTestRecord', {
    inplsh: props.data.inplsh,
    testTime: recordDate.value
  })
  if (code !== 0) return message.error(msg)
  if (!data || data.length <= 0) {
    monitorsData.value = { brId: props.data.brId, createUserName: userStore.empName, createUser: userStore.empId, time: dayjs().format('HH:mm') }
    isPrint.value = false
    return
  }
  isPrint.value = true
  monitorsData.value = { ...data }
}
const onSelectNurse = (select) => {
  monitorsData.value.createUserName = select.empName
  monitorsData.value.createUser = select.empId
}
watch(
  () => props.open,
  (val) => {
    if (val) {
      if (props.type === '转区') {
        const { transferDate, advMemo } = props.data.inpTransferZone
        formState.value = {
          ...props.data,
          zcsj: transferDate ? transferDate + ' 00:00:00' : '',
          cmemo: advMemo || ''
        }
      } else if (props.type === '血糖监测') {
        getMonitorsData()
        monitorsData.value = {
          brId: props.data.brId
        }
        formState.value = {
          ...formState.value,
          ...props.data
        }
      } else {
        formState.value = {
          dyrq: dayjs().format('YYYY-MM-DD'),
          ...props.data
        }
      }
    }
  }
)
const onCancel = () => {
  emit('update:open', false)
  emit('close')
}
</script>
<style lang="less" scoped>
.xt-style-flex {
  display: flex;
  flex-flow: row wrap;

  .ant-picker {
    width: 100%;
  }
}
</style>
